local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"
require "fishenum"
local table_insert = table.insert

local filelog = require "filelog"
local configdao = require "configdao"

local roles = {}
local Router = {
	idle_table_mng = nil,
}

function Router.forward(rid, tablesvr, table_index)
	roles[rid] = {
		table_service = tablesvr,
		table_index = table_index,
	}
	cluster.send("gatenode", ".router", "role_enter_table", rid, skynet.getenv("nodename"), table_index)
end

function Router.unforward(rid, table_index)
	local idx
	if roles[rid] then
		idx = roles[rid].table_index
		roles[rid] = nil
	else
		idx = table_index
	end
	cluster.send("gatenode", ".router", "role_leave_table", rid, skynet.getenv("nodename"), idx)
end

function Router.get_role_data(rid)
	return roles[rid]
end

function Router.get_table_allrid(idx)
	local rids = {}
	for rid, v in pairs(roles) do
		if v.table_index == idx then
			table_insert(rids, rid)
		end
	end
	return rids
end

function Router.exit_service()
	skynet.exit()
end

local function add_events(name)
	local events = require(name)
	for fn, f in pairs(events) do
		if Router[fn] then
			error("duplicate function: name " .. tostring(fn))
		end
		if type(f) == 'function' then
			if fn == "init" then
				f(Router)
			else
				Router[fn] = f
			end
		end
	end
end

-- 这里主要负责处理向桌子发起的请求
local function table_request(cmd, rid, rdata, args)
	args = args or {}
	if roles[rid] and roles[rid].table_service then
		if type(args) ~= type{} then
			filelog.sys_error("invalid args! ===>", cmd, args)
			return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "参数错误！"}
		end
		local status, retmsg = pcall(skynet.call, roles[rid].table_service, "lua", cmd, rid, rdata, args)
		if status then
			return retmsg
		else
			filelog.sys_error("call table server: " .. cmd .. " failed!", "msg: " .. (retmsg or "nil"))
			return {retcode = EErrCode.ERR_SYSTEM_ERROR, retstr = "系统错误！"}
		end
	else
		filelog.sys_error("role not in game table!", cmd)
		return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "玩家没在游戏中！"}
	end
end

local function init()
	add_events("nodecmd")
	add_events("robotmgr")
	if Router['init_table_pool'] then
		Router['init_table_pool'](configdao.get_cfgsvrs_key(skynet.getenv("nodename")))
	end
end

local function test()
	local rid = 10000
	local roledata = {
		money = {diamond = 10000},
		info = {rolename = "zld", logo = "1"}
	}
	local args = {level_type = 1}
	filelog.debug(Router.entertable(rid, roledata, args))
end

skynet.start(function()
	skynet.dispatch("lua", function (session, source, cmd, ...)
		-- filelog.debug("received commamd: ", cmd, ...)
		local f = Router[cmd]
		if type(f) == 'function' then
			skynet.retpack(f(...))
		else
			skynet.retpack(table_request(cmd, ...))
		end
	end)
	init()
	-- test()
end)

